package controllers;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import play.mvc.Controller;
import play.mvc.With;
import models.ActionItem;
import models.ActionPlan;
import models.Entities;
import models.Idea;
import models.IdeaDeveloper;
import models.Notification;
import models.Organization;
import models.Organizer;
import models.Request;
import models.Tag;
import models.Topic;
import models.Timeline;
import models.rendering;

import com.google.gson.JsonObject;
import java.text.SimpleDateFormat;

@With(Secure.class)
public class ActionPlanController extends Controller {

	/**
	 * @author Amr Gamal this method takes the actionPlanId and renders the
	 *         corresponding action plan
	 * @param actionPlanId
	 *            Id of the action plan to be rendered
	 */
	public static void ActionPlanOrganizer(long actionPlanId)
			throws ParseException {

		ActionPlan actionPlan = (ActionPlan) ActionPlan
				.find("id=?", actionPlanId).fetch().get(0);

		String developerOrOrganizer = "";
		IdeaDeveloper member = (IdeaDeveloper) IdeaDeveloper
				.find("id=?", Security.userid()).fetch().get(0);

		List<Organizer> organizer = Organizer.find("ideaDeveloper=?", member)
				.fetch();
		if (organizer.size() == 0) {
			developerOrOrganizer = "developer";
		} else if (actionPlan.managers.contains(organizer.get(0))) {
			developerOrOrganizer = "organizer";
		} else {
			developerOrOrganizer = "developer";
		}

		long actionPlanID = actionPlan.id;
		long organizerID = (long) 0.0;
		if (developerOrOrganizer.equals("developer")) {
			organizerID = member.id;
		} else {
			organizerID = organizer.get(0).id;
		}
		List<ActionItem> actionItems = actionPlan.actionItems;
		
		String itemsIds = "";
		if (actionItems.size() > 0) {
			itemsIds = "" + actionItems.get(0).id;
		}
		for (int i = 1; i < actionItems.size(); i++) {
			itemsIds += "#" + (actionItems.get(i).id);
		}

		long ideaDeveloperId = member.id;
		String planStartDay = actionPlan.startDate.toString().substring(8, 10);
		String planStartMonth = actionPlan.startDate.toString().substring(5, 7);
		String planStartYear = actionPlan.startDate.toString().substring(0, 4);
		String planEndDay = actionPlan.endDate.toString().substring(8, 10);
		String planEndMonth = actionPlan.endDate.toString().substring(5, 7);
		String planEndYear = actionPlan.endDate.toString().substring(0, 4);
		render(actionPlan, actionPlanID, organizerID, actionItems,
				developerOrOrganizer, ideaDeveloperId, planStartDay,
				planStartMonth, planStartYear, planEndDay, planEndMonth,
				planEndYear, itemsIds);

	}

	public static void ActionPlanOrganizer2() {
		ActionPlan actionPlan = new ActionPlan();
		actionPlan.name = "amr";
		actionPlan.description = "body";
		actionPlan.requirment = "req";
		actionPlan.status = "status";
		Date start = new Date(/* 110, 4, 5 */);
		Date end = new Date(/* 110, 6, 7 */);
		actionPlan.startDate = start;
		actionPlan.endDate = end;
		Organizer organizer = new Organizer();
		organizer.save();
		actionPlan.save();
		long actionPlanID = actionPlan.id;
		long organizerID = organizer.id;
		render(actionPlanID, organizerID);
	}

	public static void dummyData() {
		ActionPlan action = new ActionPlan();
		action.name = "amr";
		action.description = "body";
		action.requirment = "req";
		action.status = "status";
		action.save();
		Date start = new Date(111, 4, 5);
		Date end = new Date(111, 6, 7);
		ActionItem one = new ActionItem();
		one.title = "Amr Gamal";
		one.body = "Amr";
		one.startDate = start;
		one.endDate = end;
		one.save();
		ActionItem two = new ActionItem();
		two.title = "Ebrahim";
		two.body = "Mona";
		two.startDate = start;
		two.endDate = end;
		two.save();
		one.actionPlan = action;
		one.save();
		two.actionPlan = action;
		two.save();
		Entities entity = new Entities();
		entity.name = "Ebrahim";
		entity.views = 11;
		entity.type = "Test";
		entity.save();
		Topic t = new Topic();
		t.title = "Ebrahim Topic";
		t.description = "a test Topic";
		t.numberOfViews = 11;
		t.hidden = false;
		t.dateOfDraftingPosting = new Date();
		t.published = true;
		t.promotedForExecution = true;
		t.closed = false;
		t.save();
		Tag tag = new Tag();
		tag.name = "Ebrahim";
		tag.dateOfCreation = new Date();
		tag.save();
		Idea i = new Idea();
		i.save();
		i.ideaEnt = entity;
		i.ideaTopic = t;
		i.tags.add(tag);
		i.title = "Ebrahim Topic";
		i.description = "a test Topic";
		i.numberOfViews = 11;
		i.dateOfDraftingPosting = new Date();
		i.published = true;
		i.promotedForExecution = true;
		i.priority = "M";
		i.noOfVotes = 10;
		i.save();
		action.ideas.add(i);
		System.out.println("Size " + action.ideas.size());
		action.save();
		List<ActionItem> actionItems = new ArrayList<ActionItem>();
		actionItems.add(one);
		actionItems.add(two);
		render(action, actionItems);

	}

	/**
	 * a method that links the view assignPlanRequirmentStatus to the
	 * corresponding method in the orgaznizer class
	 * 
	 * @author Amr Gamal
	 * @param planId
	 *            id of the plan to be updated
	 * @param organizerId
	 *            id of the organizer who is updating
	 * @param req
	 *            the new requirement
	 * @param status
	 *            the new status
	 * @return void this method returns nothing
	 */
	public static void assignPlanRequirmentStatus(long planId,
			long organizerId, String req, String status) {
		JsonObject json = new JsonObject();
		ActionPlan actionPlan = (ActionPlan) ActionPlan.find("id=?", planId)
				.fetch().get(0);
		Organizer organizer = (Organizer) Organizer.find("id=?", organizerId)
				.fetch().get(0);
		String result = organizer.setPlanRequirmentsStatus(actionPlan, req,
				status);
		json.addProperty("res", result);
		String stats = actionPlan.status;
		json.addProperty("status", stats);
		String requirment = actionPlan.requirment;
		json.addProperty("req", requirment);
		renderJSON(json.toString());
	}

	/**
	 * A method the renders the ActionItem View
	 * 
	 * @author Amr Gamal
	 * @param ActionItemId
	 *            this is the Id of the Action Item that will appear in the page
	 */
	public static void ActionItem(long ActionItemId, long ActionPlanId) {
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", ActionItemId).fetch().get(0);
		String developerOrOrganizer = "";
		IdeaDeveloper member = (IdeaDeveloper) IdeaDeveloper
				.find("id=?", Security.userid()).fetch().get(0);
		List<Organizer> organizer = Organizer.find("ideaDeveloper=?", member)
				.fetch();
		if (organizer.size() == 0) {
			developerOrOrganizer = "developer";
		} else {
			developerOrOrganizer = "organizer";
		}

		render(actionItem, developerOrOrganizer, ActionPlanId);
	}

	/**
	 * A method that allows the organizer to create an action plan
	 * 
	 * @author Doaa Ramiz
	 * 
	 * @param String
	 *            name, the name of the action plan
	 * @param Idea
	 *            idea, the idea that the organizer wanted to start an action
	 *            plan with
	 * @param String
	 *            body, the body of the action plan
	 * @param Sting
	 *            startDay, the start day of the action plan
	 * @param Sting
	 *            startMonth, the start month of the action plan
	 * @param Sting
	 *            startYear, the start year of the action plan
	 * @param Sting
	 *            endDay, the end day of the action plan
	 * @param Sting
	 *            endMonth, the end month of the action plan
	 * @param Sting
	 *            endYear, the end year of the action plan
	 * @param Organizer
	 *            organizer, the organizer who will start the action plan
	 */
	public static void StartActionPlanM(String name, long ideaId,
			String description, String startDay, String startMonth,
			String startYear, String endDay, String endMonth, String endYear,
			long organizerId) {

		JsonObject msg = new JsonObject();
		Date sDate = new Date();
		Date eDate = new Date();
		sDate.setDate(Integer.parseInt(startDay));
		sDate.setMonth(Integer.parseInt(startMonth) - 1);
		sDate.setYear(Integer.parseInt(startYear) - 1900);
		eDate.setDate(Integer.parseInt(endDay));
		eDate.setMonth(Integer.parseInt(endMonth) - 1);
		eDate.setYear(Integer.parseInt(endYear) - 1900);

		Organizer organizer = (Organizer) Organizer.find("id=?", organizerId)
				.fetch().get(0);

		Idea idea = (Idea) Idea.find("id=?", ideaId).fetch().get(0);

		String result = organizer.startActionPlan(name, idea, description,
				sDate, eDate);
		organizer.save();
		msg.addProperty("res", result);

		renderJSON(msg.toString());
	}

	/**
	 * renders the StartActionPlan view
	 * 
	 * @author Doaa Ramiz
	 * 
	 * @param planId
	 *            the id of the plan the user wants to view its timeline
	 * 
	 */
	public static void StartActionPlan(long ideaId) {

		IdeaDeveloper member = (IdeaDeveloper) IdeaDeveloper
				.find("id=?", Security.userid()).fetch().get(0);
		List<Organizer> organizer = Organizer.find("ideaDeveloper=?", member)
				.fetch();

		long organizerId = organizer.get(0).id;

		render(ideaId, organizerId);
	}

	/**
	 * a method that gets the days, months and years in a dropdown list in the
	 * view and joins the model with the view for the setStartDate
	 * 
	 * @author Andrew
	 * @param planId
	 *            : the ID of the plan (got from the session)
	 * @param organizerId
	 *            :the ID of the organizer (got from the session)
	 * @year: year
	 * @mon: month
	 * @day: day
	 * @return void hing
	 */
	public static void setStartDate(long planId, long organizerId,
			String startdate) {
		String[] x = startdate.split("/");
		int y = Integer.parseInt(x[2]);
		int m = Integer.parseInt(x[0]) - 1;
		int d = Integer.parseInt(x[1]);

		JsonObject json = new JsonObject();
		ActionPlan a = (ActionPlan) ActionPlan.find("id=?", planId).fetch()
				.get(0);
		Organizer o = (Organizer) Organizer.find("id=?", organizerId).fetch()
				.get(0);
		String result = o.setStartDate(a, y, m, d);
		json.addProperty("res", result);
		renderJSON(json.toString());
	}

	/**
	 * a method that gets the days, months and years in a dropdown list in the
	 * view and joins the model with the view for the setEndDate
	 * 
	 * @author Andrew
	 * @param planId
	 *            : the ID of the plan (got from the session)
	 * @param organizerId
	 *            :the ID of the organizer (got from the session)
	 * @year: year
	 * @mon: month
	 * @day: day
	 * @return void hing
	 */
	public static void setEndDate(long planId, long organizerId, String endDate) {
		String[] x = endDate.split("/");
		int y = Integer.parseInt(x[2]);
		int m = Integer.parseInt(x[0]) - 1;
		int d = Integer.parseInt(x[1]);

		JsonObject json = new JsonObject();
		ActionPlan a = (ActionPlan) ActionPlan.find("id=?", planId).fetch()
				.get(0);
		Organizer o = (Organizer) Organizer.find("id=?", organizerId).fetch()
				.get(0);
		String result = o.setEndDate(a, y, m, d);
		json.addProperty("res", result);
		renderJSON(json.toString());
	}

	public static void getDates(long planID) {
		String result = "";
		ActionPlan a = (ActionPlan) ActionPlan.find("id=?", planID).fetch()
				.get(0);
		result += ("Start date:" + DateFormat
				.getDateInstance(DateFormat.MEDIUM).format(a.startDate));
		result += "\n";
		result += ("End date:" + DateFormat.getDateInstance(DateFormat.MEDIUM)
				.format(a.endDate));
		JsonObject json = new JsonObject();
		json.addProperty("res", result);
		renderJSON(json.toString());

	}

	/**
	 * A method that allows the user to view the timeline
	 * 
	 * @author Doaa Ramiz
	 * 
	 * @param planId
	 *            the id of the plan the user wants to view its timeline
	 * 
	 * @throws IOException
	 * 
	 * @throws parseException
	 */
	public static void Timeline(long actionPlanId) throws IOException,
			ParseException {

		ActionPlan p = (ActionPlan) ActionPlan.find("id=?", actionPlanId)
				.fetch().get(0);

		FileWriter fstream;
		fstream = new FileWriter("IdeaManagement/public/xml/jfk.xml");

		BufferedWriter out = new BufferedWriter(fstream);

		out.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		out.write("\n");
		out.write("<data>");
		out.write("\n");

		out.write("<event start=\"");
		// out.write(itemsList.get(i).startDate.toGMTString());
		String inputDate = (p.startDate.toGMTString());
		Date date = new SimpleDateFormat("dd MMM yyyy HH:mm:ss zzz")
				.parse(inputDate);

		out.write(new SimpleDateFormat("MMM dd yyyy HH:mm:ss Z").format(date));

		out.write("\"");

		out.write(" ");
		out.write("title=\"");
		out.write(p.name + " start date");
		out.write("\"");
		out.write(" ");
		out.write("icon=\"/public/images/dark-red-circle.png\"");
		out.write(">");

		out.write("</event>");
		out.write("\n");

		out.write("<event start=\"");
		// out.write(itemsList.get(i).startDate.toGMTString());
		inputDate = (p.endDate.toGMTString());
		date = new SimpleDateFormat("dd MMM yyyy HH:mm:ss zzz")
				.parse(inputDate);

		out.write(new SimpleDateFormat("MMM dd yyyy HH:mm:ss Z").format(date));

		out.write("\"");
		out.write(" ");

		out.write("title=\"");
		out.write(p.name + " end date");
		out.write("\"");
		out.write(" ");
		out.write("icon=\"/public/images/dark-red-circle.png\"");
		out.write(">");

		out.write("</event>");
		out.write("\n");

		for (int i = 0; i < p.actionItems.size(); i++) {
			out.write("<event start=\"");
			// out.write(itemsList.get(i).startDate.toGMTString());
			inputDate = (p.actionItems.get(i).startDate.toGMTString());
			date = new SimpleDateFormat("dd MMM yyyy HH:mm:ss zzz")
					.parse(inputDate);
			date.setTime(date.getTime()+86400000);

			out.write(new SimpleDateFormat("MMM dd yyyy HH:mm:ss Z")
					.format(date));
			out.write("\"");
			out.write(" ");
			out.write("end=\"");

			// out.write(itemsList.get(i).endDate.toGMTString());
			inputDate = (p.actionItems.get(i).endDate.toGMTString());
			date = new SimpleDateFormat("dd MMM yyyy HH:mm:ss zzz")
					.parse(inputDate);
			out.write(new SimpleDateFormat("MMM dd yyyy HH:mm:ss Z")
					.format(date));

			out.write("\"");
			out.write(" ");
			out.write("title=\"");
			// out.write( p.actionItems.get(i).actionPlan);
			out.write(p.actionItems.get(i).title);
			out.write("\"");
			out.write(">");
			out.write(p.actionItems.get(i).body);
			out.write("</event>");
			out.write("\n");

		}

		out.write("</data>");
		out.flush();
		out.close();

		render();
	}

	/**
	 * It's a method that shows the Entites related to this ActionItem
	 * 
	 * @author Ebrahim
	 * @param actionItemId
	 *            :It's the Id of the actionItem
	 * 
	 * 
	 * */
	public static void relatedEntities(long actionItemId) {
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		render(actionItem.entities);
	}

	/**
	 * It's a method that shows the Topics related to this ActionItem
	 * 
	 * @author Ebrahim
	 * @param actionItemId
	 *            :It's the Id of the actionItem
	 * 
	 * 
	 * */
	public static void relatedTopics(long actionItemId) {
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		render(actionItem.topics);
	}

	/**
	 * It's a method that shows the Tags related to this ActionItem
	 * 
	 * @author Ebrahim
	 * @param actionItemId
	 *            :It's the Id of the actionItem
	 * 
	 * 
	 * */
	public static void relatedTags(long actionItemId) {
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		render(actionItem.tags);
	}

	/**
	 * It's a method that passes Entities related to actionplan to relate them
	 * to actionItem
	 * 
	 * @author Ebrahim
	 * @param actionItemId
	 *            :It's the Id of the actionItem
	 * 
	 * 
	 * */
	public static void relateToEntities(long actionItemId) {
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		Organization org = (Organization) Organization
				.find("id=?", actionItem.actionPlan.organizationId).fetch()
				.get(0);
		List<Entities> entities = org.liesIn;
		List<Entities> actionItemEntities = actionItem.entities;
		for (int i = 0; i < entities.size(); i++) {
			for (int j = 0; j < actionItemEntities.size(); j++) {
				if (entities.get(i).equals(actionItemEntities.get(j))) {
					entities.remove(i);
				}
			}
		}
		render(entities, actionItemId);
	}

	/**
	 * It's a method that passes Topics related to actionplan to relate them to
	 * actionItem
	 * 
	 * @author Ebrahim
	 * @param actionItemId
	 *            :It's the Id of the actionItem
	 * 
	 * 
	 * */
	public static void relateToTopics(long actionItemId) {
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		Organization org = (Organization) Organization
				.find("id=?", actionItem.actionPlan.organizationId).fetch()
				.get(0);
		List<Topic> actionItemTopics = actionItem.topics;
		List<Topic> topics = org.topics;
		for (int i = 0; i < topics.size(); i++) {
			for (int j = 0; j < actionItemTopics.size(); j++) {
				if (topics.get(i).equals(actionItemTopics.get(j))) {
					topics.remove(i);
				}
			}
		}
		render(topics, actionItemId);

	}

	/**
	 * It's a method that passes Tags related to actionplan to relate them to
	 * actionItem
	 * 
	 * @author Ebrahim
	 * @param actionItemId
	 *            :It's the Id of the actionItem
	 * 
	 * 
	 * */
	public static void relateToTags(long actionItemId) {
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		List<Tag> actionItemTags = actionItem.tags;
		List<Tag> tags = new ArrayList<Tag>();
		ActionPlan actionPlan = actionItem.actionPlan;
		List<Idea> ideas = new ArrayList<Idea>();
		if (actionPlan != null) {
			ideas = actionPlan.ideas;
		}
		for (int i = 0; i < ideas.size(); i++) {
			for (int j = 0; j < ideas.get(i).tags.size(); j++) {
				if (!actionItemTags.contains(ideas.get(i).tags.get(j)))
					tags.add(ideas.get(i).tags.get(j));
			}
		}
		render(tags, actionItemId);
	}

	/**
	 * It's a method that passes the choosen topic by the user to relate it to
	 * actionItem
	 * 
	 * @author Ebrahim
	 * @param topicId
	 *            :it's the Id of the topic that should be related to the
	 *            actionItem.
	 * @param actionItemId
	 *            :It's the Id of the actionItem
	 * 
	 * 
	 * */
	public static void addTopic(long topicId, long actionItemId) {
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		Topic topic = (Topic) Topic.find("id=?", topicId).fetch().get(0);
		actionItem.topics.add(topic);
		actionItem.save();
	}

	/**
	 * It's a method that passes the choosen Entity by the user to relate it to
	 * actionItem
	 * 
	 * @author Ebrahim
	 * @param entityId
	 *            :it's the Id of the entity that should be related to the
	 *            actionItem.
	 * @param actionItemId
	 *            :It's the Id of the actionItem
	 * 
	 * 
	 * */
	public static void addEntity(long entityId, long actionItemId) {
		System.out.println("This the entity ID " + entityId);
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		Entities entity = (Entities) Entities.find("id=?", entityId).fetch()
				.get(0);
		actionItem.entities.add(entity);
		actionItem.save();
	}

	/**
	 * It's a method that passes the choosen tag by the user to relate it to
	 * actionItem
	 * 
	 * @author Ebrahim
	 * @param tagId
	 *            :it's the Id of the tag that should be related to the
	 *            actionItem.
	 * @param actionItemId
	 *            :It's the Id of the actionItem
	 * 
	 * 
	 * */
	public static void addTag(long tagId, long actionItemId) {
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		Tag tag = (Tag) Tag.find("id=?", tagId).fetch().get(0);
		actionItem.tags.add(tag);
		actionItem.save();

	}

	/**
	 * Notifies the user with the action plan that another users wants to share
	 * with
	 * 
	 * @author Mohamed Sekkina
	 * @param reciverUserName
	 *            String, The username of the user the topic to be shared with
	 * @param actionPlanId
	 *            long, The id of the action plan the user wants to share
	 */
	public static void shareActionPlan(String recieverUserName,
			long actionPlanId) {
		JsonObject response = new JsonObject();
		IdeaDeveloper reciever = new IdeaDeveloper();
		ActionPlan actionPlanToShare = new ActionPlan();
		IdeaDeveloper sender = new IdeaDeveloper();
		Idea idea = new Idea();
		try {
			reciever = IdeaDeveloper.find("username=?", recieverUserName)
					.first();
			actionPlanToShare = ActionPlan.findById(actionPlanId);
			sender = IdeaDeveloper.find("username=?", Security.connected())
					.first();
		} catch (Exception e) {
			response.addProperty("response",
					"Sorry, you can't share the actionPlan with that user!");
			renderJSON(response.toString());
			return;
		}
		if (!IdeaDeveloper.canViewActionPlan(reciever, actionPlanToShare)) {
			response.addProperty("response",
					"Sorry, this user is not authorized to view this actionPlan!");
		} else {
			String body = " has shared this actionPlan : <a href=\"http://localhost:9000/actionplancontroller/actionplanorganizer?actionPlanId="
					+ actionPlanId + "\">" + actionPlanToShare.name + "</a>";
			Notification.notify(body, reciever, sender, new Date());
			response.addProperty("response", "Shared successfully!");
		}
		renderJSON(response.toString());
	}

	/**
	 * a method that allows an IdeaDeveloper to volunteer to work on an action
	 * Item by sending a justified request
	 * 
	 * @author Amr Gamal
	 * @param ideaDeveloperId
	 *            the ID of the idea developer doing the request
	 * @param actionItemId
	 *            the ID of the actionItem the IdeaDeveloper requests to
	 *            volunteer on
	 * @param body
	 *            the body of the request
	 * @return void the method returns nothing
	 */
	public static void volunteerToWorkOnActionItem(long ideaDeveloperId,
			long actionItemId, String body) {
		JsonObject json = new JsonObject();
		IdeaDeveloper ideaDeveloper = (IdeaDeveloper) IdeaDeveloper
				.find("id=?", ideaDeveloperId).fetch().get(0);
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		String result = ideaDeveloper.volunteerOnActionItem(actionItem, body);
		json.addProperty("res", result);
		renderJSON(json.toString());

	}

	/**
	 * a method that assigns an ideadeveloper to an actionplan
	 * 
	 * @author Andrew
	 * 
	 * @param planId
	 *            the ID of the plan
	 * @param organizerId
	 *            the ID of the organizer
	 * @param ideaDevId
	 *            the id of the ideadeveloper
	 * @return void
	 */
	public static void assignIdeaDevToPlan(long planId, long organizerId,
			long IdeaDevId) {
		JsonObject json = new JsonObject();
		ActionPlan a = (ActionPlan) ActionPlan.find("id=?", planId).fetch()
				.get(0);
		Organizer o = (Organizer) Organizer.find("id=?", organizerId).fetch()
				.get(0);
		IdeaDeveloper idev = (IdeaDeveloper) IdeaDeveloper
				.find("id=?", IdeaDevId).fetch().get(0);

		String result = o.assignIdeaDevToPlan(a, idev);
		json.addProperty("res", result);
		renderJSON(json.toString());
	}

	/**
	 * a method that renders a list of ideadevelopers who are allowed to be
	 * assigned to a plan
	 * 
	 * @author Andrew
	 * 
	 * @param planId
	 *            the ID of the plan
	 * @return void
	 */
	public static void recentlyAddedIdeaDevs(long actionPlanID) {
		ActionPlan a = (ActionPlan) ActionPlan.find("id=?", actionPlanID)
				.fetch().get(0);
		Organization arg = (Organization) Organization
				.find("id=?", a.organizationId).fetch().get(0);
		List<IdeaDeveloper> ideaDevList = arg.members;
		for (int i = 0; i < ideaDevList.size(); i++) {
			if (arg.blocked.contains(ideaDevList.get(i))) {
				ideaDevList.remove(i);
			}

		}
		for (int i = 0; i < a.volunteers.size(); i++) {

			if (ideaDevList.contains(a.volunteers.get(i))) {
				ideaDevList.remove(a.volunteers.get(i));
			}

		}
		rendering res[] = new rendering[ideaDevList.size()];
		for (int i = 0; i < res.length; i++) {
			res[i] = (new rendering(ideaDevList.get(i).fullName,
					ideaDevList.get(i).id));
		}
		renderJSON(res);
	}

	/**
	 * a method that joins the model with the view for the assignIdeaToPlan
	 * 
	 * @author Andrew
	 * @param planId
	 *            : the ID of the plan (got from the session)
	 * @param organizerId
	 *            :the ID of the organizer (got from the session)
	 * @param IdeaID
	 *            :the ID of the Idea
	 * @return void hing
	 */
	public static void assignIdeaToPlan(long planId, long organizerId,
			long IdeaId) {
		JsonObject json = new JsonObject();
		ActionPlan a = (ActionPlan) ActionPlan.find("id=?", planId).fetch()
				.get(0);
		Organizer o = (Organizer) Organizer.find("id=?", organizerId).fetch()
				.get(0);
		Idea i = (Idea) Idea.find("id=?", IdeaId).fetch().get(0);
		String result = o.assignIdeaToPlan(a, i);
		json.addProperty("res", result);
		renderJSON(json.toString());
	}

	/**
	 * a method that renders a list of ideas which are allowed to be assigned to
	 * a plan
	 * 
	 * @author Andrew
	 * 
	 * @param planId
	 *            the ID of the plan
	 * @return void
	 */
	public static void recentlyAddedIdeas(long actionPlanID) {
		ActionPlan a = (ActionPlan) ActionPlan.find("id=?", actionPlanID)
				.fetch().get(0);
		Organization arg = (Organization) Organization
				.find("id=?", a.organizationId).fetch().get(0);
		List<Idea> ideaList = arg.ideas;

		for (int i = 0; i < a.ideas.size(); i++) {

			if (ideaList.contains(a.ideas.get(i))) {
				ideaList.remove(a.ideas.get(i));
			}
		}

		rendering res[] = new rendering[ideaList.size()];
		for (int i = 0; i < res.length; i++) {
			res[i] = (new rendering(ideaList.get(i).title, ideaList.get(i).id));
		}

		renderJSON(res);
	}

	/**
	 * a method that renders a list of ideaDevelopers who are already assigned
	 * to a plan
	 * 
	 * @author Andrew
	 * 
	 * @param planId
	 *            the ID of the plan
	 * @return void
	 */
	public static void getPlanIdeaDevs(long actionPlanID) {
		ActionPlan a = (ActionPlan) ActionPlan.find("id=?", actionPlanID)
				.fetch().get(0);
		List<IdeaDeveloper> ideaDevList = a.volunteers;
		String[] res = new String[ideaDevList.size()];
		rendering[] rez = new rendering[ideaDevList.size()];
		for (int i = 0; i < ideaDevList.size(); i++) {
			res[i] = ideaDevList.get(i).fullName;
			rez[i] = new rendering(ideaDevList.get(i).fullName,
					ideaDevList.get(i).id);
		}

		renderJSON(rez);
	}

	/**
	 * a method that renders a list of ideas which are already assigned to the
	 * plan
	 * 
	 * @author Andrew
	 * 
	 * @param planId
	 *            the ID of the plan
	 * @return void
	 */
	public static void getPlanIdeas(long actionPlanID) {
		ActionPlan a = (ActionPlan) ActionPlan.find("id=?", actionPlanID)
				.fetch().get(0);
		List<Idea> ideaList = a.ideas;
		String[] res = new String[ideaList.size()];
		rendering[] rez = new rendering[ideaList.size()];
		for (int i = 0; i < ideaList.size(); i++) {
			res[i] = ideaList.get(i).title;
			rez[i] = new rendering(ideaList.get(i).title, ideaList.get(i).id);

		}

		renderJSON(rez);
	}

	/**
	 * a method that allows the organizer to accept the volunteer request
	 * 
	 * @author Amr Gamal
	 * @param organizerId
	 *            Id of the organizer
	 * @param requestId
	 *            Id of the request to be accepted
	 */

	public static void acceptVolunteerRequest(long organizerId, long requestId) {
		// JsonObject json = new JsonObject();
		// Organizer organizer = (Organizer) Organizer.find("id=?", organizerId)
		// .fetch().get(0);
		// String result = organizer.approveRequest(requestId);
		// json.addProperty("res", result);
		// renderJSON(json.toString());

		JsonObject json = new JsonObject();
		Organizer organizer = (Organizer) Organizer.find("id=?", organizerId)
				.fetch().get(0);
		Request requestToAccept = Request.findById(requestId);
		long id = requestToAccept.id;
		json.addProperty("hello", id);

		requestToAccept.item.requests.remove(requestToAccept);
		requestToAccept.item.save();
		requestToAccept.dev.requests.remove(requestToAccept);
		requestToAccept.dev.save();
		requestToAccept.item.volunteers.add(requestToAccept.dev);
		requestToAccept.item.save();
		requestToAccept.dev.actionItem.add(requestToAccept.item);
		requestToAccept.dev.save();
		requestToAccept.delete();
		// requestToAccept.accept2();
		// Notification.notify("volunteer", null, null, null);

		// String result =organizer.approveRequest(requestId);

		json.addProperty("res", "accepted");
		renderJSON(json.toString());
	}

	/**
	 * 
	 * a method that allows the organizer to reject the volunteer request
	 * 
	 * @author Amr Gamal
	 * @param organizerId
	 *            Id of the organizer
	 * @param requestId
	 *            Id of the request to be rejected
	 */

	public static void rejectVolunteerRequest(long organizerId, long requestId) {
		JsonObject json = new JsonObject();
		Organizer organizer = (Organizer) Organizer.find("id=?", organizerId)
				.fetch().get(0);
		Request requestToReject = Request.findById(requestId);
		requestToReject.item.requests.remove(requestToReject);
		requestToReject.item.save();
		requestToReject.dev.requests.remove(requestToReject);
		requestToReject.dev.save();
		requestToReject.item.volunteers.add(requestToReject.dev);
		requestToReject.item.save();
		requestToReject.dev.actionItem.add(requestToReject.item);
		requestToReject.dev.save();
		requestToReject.delete();
		// requestToAccept.accept2();
		// Notification.notify("volunteer", null, null, null);

		// String result =organizer.approveRequest(requestId);

		json.addProperty("res", "rejected");
		renderJSON(json.toString());
	}

	/**
	 * this method gets a list of volunteer requests associated with an action
	 * item
	 * 
	 * @author Amr Gamal
	 * @param actionItemId
	 *            Id of the action item
	 */
	public static void getActionItemRequests(long actionItemId) {
		ActionItem actionItem = (ActionItem) ActionItem
				.find("id=?", actionItemId).fetch().get(0);
		List<Request> requests = actionItem.requests;
		String req = "";
		String reqId = "";
		if (requests.size() > 0) {
			req = requests.get(0).dev.username + ":" + requests.get(0).body;
			reqId = "" + requests.get(0).id;
		}

		for (int i = 1; i < requests.size(); i++) {
			req += "&" + requests.get(i).dev.username + ":"
					+ requests.get(i).body;
			reqId = "&" + requests.get(i).id;
		}
		JsonObject json = new JsonObject();
		json.addProperty("requests", req);
		json.addProperty("requestsIds", reqId);
		renderJSON(json.toString());

	}

	/**
	 * 
	 * a method that renders the calendar
	 * 
	 * @author Amr Gamal
	 * @param actionPlanId
	 *            the Id of the action plan to which the calendar belongs
	 */

	public static void CalenderNew(long actionPlanId) {
		ActionPlan actionPlan = (ActionPlan) ActionPlan
				.find("id=?", actionPlanId).fetch().get(0);
		List<ActionItem> actionItems = actionPlan.actionItems;

		String startDay = "";
		String startMonth = "";
		String startYear = "";
		String endDay = "";
		String endMonth = "";
		String endYear = "";

		String itemsIds = "";
		String itemsBody = "";
		if (actionItems.size() > 0) {

			startDay = actionItems.get(0).startDate.toString().substring(8, 10);
			startMonth = actionItems.get(0).startDate.toString()
					.substring(5, 7);
			startYear = actionItems.get(0).startDate.toString().substring(0, 4);
			endDay = actionItems.get(0).endDate.toString().substring(8, 10);
			endMonth = actionItems.get(0).endDate.toString().substring(5, 7);
			endYear = actionItems.get(0).endDate.toString().substring(0, 4);

			itemsBody = actionItems.get(0).body;
			itemsIds = "" + actionItems.get(0).id;
		}

		for (int i = 1; i < actionItems.size(); i++) {
			itemsIds += "#" + (actionItems.get(i).id);
			itemsBody += "#" + (actionItems.get(i).body);
			startDay += "#"
					+ (actionItems.get(i).startDate.toString().substring(8, 10));
			startMonth += "#"
					+ (actionItems.get(i).startDate.toString().substring(5, 7));
			startYear += "#"
					+ (actionItems.get(i).startDate.toString().substring(0, 4));
			endDay += "#"
					+ (actionItems.get(i).endDate.toString().substring(8, 10));
			endMonth += "#"
					+ (actionItems.get(i).endDate.toString().substring(5, 7));
			endYear += "#"
					+ (actionItems.get(i).endDate.toString().substring(0, 4));

		}
		String developerOrOrganizer = "";
		IdeaDeveloper ideaDeveloperId = (IdeaDeveloper) IdeaDeveloper
				.find("id=?", Security.userid()).fetch().get(0);

		List<Organizer> organizer = Organizer.find("ideaDeveloper=?",
				ideaDeveloperId).fetch();
		long organizerID = (long) 0.0;
		if (organizer.size() == 0) {
			developerOrOrganizer = "developer";
		} else {
			developerOrOrganizer = "organizer";
			organizerID = organizer.get(0).id;
		}
		render(actionPlan, organizerID, itemsBody, actionItems, itemsIds,
				developerOrOrganizer, startDay, startMonth, startYear, endDay,
				endMonth, endYear, ideaDeveloperId);
	}

	/*
	 * @author Andrew
	 */
	public static void getStartAndEndDatesDetails(long PlanID) {

		ActionPlan actionPlan = (ActionPlan) ActionPlan.find("id=?", PlanID)
				.fetch().get(0);
		int PlanStartDay = actionPlan.startDate.getDate();
		int PlanStartMonth = actionPlan.startDate.getMonth();
		int PlanStartYear = actionPlan.startDate.getYear();

		int PlanEndDay = actionPlan.endDate.getDate();
		int PlanEndMonth = actionPlan.endDate.getMonth();
		int PlanEndYear = actionPlan.endDate.getYear();

		int[] dates = { PlanStartDay, PlanStartMonth, PlanStartYear,
				PlanEndDay, PlanEndMonth, PlanEndYear };
		renderJSON(dates);
	}

	public static void CreateActionItem(long planId, long organizerId,
			String title, String body, String ItemStartDate, String ItemEndDate) {
		ActionPlan a = (ActionPlan) ActionPlan.find("id=?", planId).fetch()
				.get(0);
		Organizer o = (Organizer) Organizer.find("id=?", organizerId).fetch()
				.get(0);

		String[] startD = ItemStartDate.split("/");
		int yStart = Integer.parseInt(startD[2]);
		int mStart = Integer.parseInt(startD[0]) - 1;
		int dStart = Integer.parseInt(startD[1]);

		String[] endD = ItemEndDate.split("/");
		int yEnd = Integer.parseInt(endD[2]);
		int mEnd = Integer.parseInt(endD[0]) - 1;
		int dEnd = Integer.parseInt(endD[1]);

		Date startDate = new Date((yStart - 1900), mStart, dStart);
		Date endDate = new Date((yEnd - 1900), mEnd, dEnd);

		String resultCreate = o.CreateActionItem(a, title, body, startDate,
				endDate);

		JsonObject json = new JsonObject();
		json.addProperty("result", resultCreate);
		renderJSON(json.toString());

	}
	/**
	 * a method that relates a topic to an actionitem
	 * 
	 * @author Andrew
	 * 
	 * @param itemID
	 *            the ID of the action item
	 * @param organizerId
	 *            the ID of the organizer
	 * @param ideaDevId
	 *            the id of the ideadeveloper
	 * @return void
	 */
	public static void relateItemToTopic(long itemID, long organizerId,
			long topicID) {
		JsonObject json = new JsonObject();
		ActionItem a = (ActionItem) ActionItem.find("id=?", itemID).fetch()
				.get(0);
		Organizer o = (Organizer) Organizer.find("id=?", organizerId).fetch()
				.get(0);
		Topic topic = (Topic) Topic.find("id=?", topicID).fetch().get(0);

		String result = o.relateItemToTopic(a, topic);
		json.addProperty("res", result);
		renderJSON(json.toString());
	}

	/**
	 * a method that renders a list of topics which are allowed to be related to an actionitem
	 * 
	 * @author Andrew
	 * 
	 * @param actionItemID
	 *            the ID of the Item
	 * @return void
	 */
	public static void addedTopics(long actionItemID) {
		ActionItem a = (ActionItem) ActionItem.find("id=?", actionItemID).fetch().get(0);
		Organization arg = (Organization) Organization.find("id=?", a.actionPlan.organizationId).fetch().get(0);
		
		List<Topic> topicList = arg.topics;
		for(int i=0;i<arg.liesIn.size();i++)
			topicList.addAll(arg.liesIn.get(i).topics);
			
	
		for (int i = 0; i < a.topics.size(); i++) {

			if (topicList.contains(a.topics.get(i))) {
				topicList.remove(a.topics.get(i));
			}

		}
		rendering res[] = new rendering[topicList.size()];
		for (int i = 0; i < res.length; i++) {
			res[i] = (new rendering(topicList.get(i).title,
					topicList.get(i).id));
		}
		renderJSON(res);
	}
	/**
	 * a method that renders a list of topics which are related to a given item
	 * 
	 * @author Andrew
	 * 
	 * @param itemID
	 *            the ID of the plan
	 * @return void
	 */
	public static void getTopicsRelatedToItem(long actionItemID) {
		ActionItem a = (ActionItem) ActionItem.find("id=?", actionItemID)
				.fetch().get(0);
		List<Topic> topicList = a.topics;
		String[] res = new String[topicList.size()];
		rendering[] rez = new rendering[topicList.size()];
		for (int i = 0; i < topicList.size(); i++) {
			res[i] = topicList.get(i).title;
			rez[i] = new rendering(topicList.get(i).title,
					topicList.get(i).id);
		}

		renderJSON(rez);
	}
}
